package cn.appsys.controller.developer;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONArray;
import com.mysql.jdbc.StringUtils;

import cn.appsys.pojo.AppCategory;
import cn.appsys.pojo.AppInfo;
import cn.appsys.pojo.AppVersion;
import cn.appsys.pojo.DataDictionary;
import cn.appsys.pojo.DevUser;
import cn.appsys.service.AppCategoryService;
import cn.appsys.service.AppInfoService;
import cn.appsys.service.AppVersionService;
import cn.appsys.service.DataDictionaryService;
import cn.appsys.tools.Constants;
import cn.appsys.tools.PageSupport;

@Controller
@RequestMapping("dev/flatform/app/")
public class AppInfoController {

	@Resource
	public AppInfoService appInfoService;

	@Resource
	public DataDictionaryService dataDictionaryService;

	@Resource
	public AppCategoryService appCategoryService;

	@Resource
	public AppVersionService appVersionService;

	/**
	 * 显示App信息管理维护
	 * 
	 * @return
	 */
	@RequestMapping(value = "/list")
	public String list(@RequestParam(value = "querySoftwareName", required = false) String softwareName,
			@RequestParam(value = "queryStatus", required = false) String statusName,
			@RequestParam(value = "queryFlatformId", required = false) String flatformName,
			@RequestParam(value = "queryCategoryLevel1", required = false) String categoryLevel1Name,
			@RequestParam(value = "queryCategoryLevel2", required = false) String categoryLevel2Name,
			@RequestParam(value = "queryCategoryLevel3", required = false) String categoryLevel3Name,
			HttpServletRequest request, @RequestParam(value = "pageIndex", required = false) String pageIndex) {
		// 查询基础信息表
		List<AppInfo> appInfoList = new ArrayList<AppInfo>();
		// 设置页面容量
		int pageSize = Constants.pageSize;
		// 当前页码
		int currentPageNo = 1;
		if (pageIndex != null) {
			try {
				currentPageNo = Integer.valueOf(pageIndex);
			} catch (NumberFormatException e) {
				return "redirect:/error";
			}
		} else {
			currentPageNo = 0;
		}
		// 总数量（表）
		int totalCount = appInfoService.devUserCount(flatformName, categoryLevel1Name, categoryLevel2Name,
				categoryLevel3Name, statusName, softwareName);
		// 总页数
		PageSupport pages = new PageSupport();
		pages.setCurrentPageNo(currentPageNo);
		pages.setPageSize(pageSize);
		pages.setTotalCount(totalCount);

		int totalPageCount = pages.getTotalPageCount();

		// 控制首页和尾页
		if (currentPageNo < 1) {
			currentPageNo = 1;
		} else if (currentPageNo > totalPageCount) {
			currentPageNo = totalPageCount;
		}
		int currentPageNos = (currentPageNo - 1) * pageSize;
		// 查询App状态
		List<DataDictionary> statusList = new ArrayList<DataDictionary>();
		statusList = dataDictionaryService.appStatusList();

		// 查询所属平台
		List<DataDictionary> flatFormList = new ArrayList<DataDictionary>();
		flatFormList = dataDictionaryService.flatformList();

		// 查询一级标签
		List<AppCategory> categoryLevel1List = new ArrayList<AppCategory>();
		categoryLevel1List = appCategoryService.categoryLevel(null);

		//二级分类列表和三级分类列表---回显
		if(categoryLevel2Name != null && !categoryLevel2Name.equals("")){
			List<AppCategory> categoryLevel2List = appCategoryService.categoryLevel(Integer.parseInt(categoryLevel1Name));
			request.setAttribute("categoryLevel2List", categoryLevel2List);
		}
		if(categoryLevel3Name != null && !categoryLevel3Name.equals("")){
			List<AppCategory> categoryLevel3List = appCategoryService.categoryLevel(Integer.parseInt(categoryLevel2Name));
			request.setAttribute("categoryLevel3List", categoryLevel3List);
		}
		
		// 查询App基础信息
		appInfoList = appInfoService.list(flatformName, categoryLevel1Name, categoryLevel2Name, categoryLevel3Name,
				statusName, softwareName, currentPageNos, pageSize);
		request.setAttribute("categoryLevel1List", categoryLevel1List);
		request.setAttribute("statusList", statusList);
		request.setAttribute("flatFormList", flatFormList);
		request.setAttribute("appInfoList", appInfoList);
		request.setAttribute("pages", pages);
		request.setAttribute("queryStatus", statusName);
		request.setAttribute("queryFlatformId", flatformName);
		request.setAttribute("queryCategoryLevel1", categoryLevel1Name);
		request.setAttribute("queryCategoryLevel2", categoryLevel2Name);
		request.setAttribute("queryCategoryLevel3", categoryLevel3Name);

		return "developer/appinfolist";
	}

	/**
	 * 查询分级
	 * 
	 * @param parentId
	 * @return
	 */
	@RequestMapping(value = "/categorylevellist.json", produces = "application/json; charset=utf-8")
	@ResponseBody
	public Object level(@RequestParam(value = "pid", required = true) Integer parentIds) {
		Map<String, Object> map = null;
		List<Object> list = new ArrayList<Object>();
		List<AppCategory> appCateList = appCategoryService.categoryLevel(parentIds);
		for (AppCategory appCategory : appCateList) {
			map = new HashMap<String, Object>();
			map.put("id", appCategory.getId());
			map.put("categoryName", appCategory.getCategoryName());
			list.add(map);
		}
		return JSONArray.toJSONString(list);
	}

	/**
	 * 查询平台
	 * 
	 * @param parentId
	 * @return
	 */
	@RequestMapping(value = "/datadictionarylist.json", produces = "application/json; charset=utf-8")
	@ResponseBody
	public Object flatFormName(Integer tcode) {
		Map<String, Object> map = null;
		List<Object> list = new ArrayList<Object>();
		// 查询所属平台
		List<DataDictionary> flatFormList = new ArrayList<DataDictionary>();
		flatFormList = dataDictionaryService.flatformList();
		for (DataDictionary dataDictionary : flatFormList) {
			map = new HashMap<String, Object>();
			map.put("valueId", dataDictionary.getValueId());
			map.put("valueName", dataDictionary.getValueName());
			list.add(map);
		}
		return JSONArray.toJSONString(list);
	}

	/**
	 * 错误页面
	 * 
	 * @return
	 */
	@RequestMapping("error")
	public String error() {
		return "403";
	}

	/**
	 * 显示增加页面
	 * 
	 * @return
	 */
	@RequestMapping(value = "appinfoadd")
	public String appInfoAdd(HttpServletRequest request) {
		// 查询所属平台
		List<DataDictionary> flatFormList = new ArrayList<DataDictionary>();
		flatFormList = dataDictionaryService.flatformList();
		request.setAttribute("flatFormList", flatFormList);
		return "developer/appinfoadd";
	}

	/**
	 * 判断APKName是否唯一
	 * 
	 * @param apkName
	 * @return
	 */
	@RequestMapping(value = "/apkexist.json", produces = "application/json; charset=utf-8")
	@ResponseBody
	public Object findApkName(String APKName) {
		HashMap<String, String> resultMap = new HashMap<String, String>();
		if (StringUtils.isNullOrEmpty(APKName)) {
			resultMap.put("APKName", "empty");
		} else {
			AppInfo appInfo = new AppInfo();
			appInfo = appInfoService.getAppInfo(null, APKName);
			if (null != appInfo)
				resultMap.put("APKName", "exist");
			else
				resultMap.put("APKName", "noexist");
		}
		return JSONArray.toJSONString(resultMap);
	}

	/**
	 * 增加App基础信息
	 * 
	 * @param appInfo
	 * @param session
	 * @param attach
	 * @param model
	 * @return
	 */
	@RequestMapping("appinfoaddsave")
	public String appInfoAddSave(AppInfo appInfo, HttpSession session,
			@RequestParam(value = "a_logoPicPath", required = false) MultipartFile attach, Model model) {
		String idPicPath = null;
		String logoLocPath = null;
		// 判断文件是否为空
		if (!attach.isEmpty()) {
			String path = session.getServletContext().getRealPath("statics" + File.separator + "uploadfiles");
			String oldFileName = attach.getOriginalFilename();// 原文件
			String prefix = FilenameUtils.getExtension(oldFileName);// 原文件后缀名
			int filesize = 500000;
			if (attach.getSize() > filesize) {
				model.addAttribute("fileUploadError", "*上传大小不得超过500KB");
				return "developer/appinfoadd";
			} else if (prefix.equalsIgnoreCase("jpg") || prefix.equalsIgnoreCase("png")
					|| prefix.equalsIgnoreCase("jpeg") || prefix.equalsIgnoreCase("pneg")) {
				String fileName = appInfo.getAPKName() + ".jpg";
				File targetFile = new File(path, fileName);
				if (!targetFile.exists()) {
					targetFile.mkdirs();
				}
				try {
					attach.transferTo(targetFile);
				} catch (Exception e) {
					e.printStackTrace();
					model.addAttribute("fileUploadError", "上传失败！");
					return "developer/appinfoadd";
				}
				idPicPath = "/AppInfoSystem/statics/uploadfiles/" + fileName;
				logoLocPath = path + File.separator + fileName;
			} else {
				model.addAttribute("fileUploadError", "* 上传图片格式不正确！");
				return "developer/appinfoadd";
			}
		}
		appInfo.setCreationDate(new Date());
		appInfo.setLogoLocPath(logoLocPath);
		appInfo.setLogoPicPath(idPicPath);
		appInfo.setCreatedBy(((DevUser) session.getAttribute(Constants.USER_SESSION)).getId());
		int result = appInfoService.add(appInfo);
		if (result > 0) {
			return "redirect:list";
		} else {
			return "redirect:appinfoadd";
		}
	}

	/**
	 * 根据id查看App信息基础
	 * 
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "appview/{id}")
	public String appView(@PathVariable Integer id, Model model) {
		// 根据id查看App基础信息
		AppInfo appInfo = new AppInfo();
		appInfo = appInfoService.getAppInfo(id, null);
		model.addAttribute("appInfo", appInfo);

		// 根据id查看App历史版本
		List<AppVersion> appVersionList = new ArrayList<AppVersion>();
		appVersionList = appVersionService.getIdVersions(id);
		model.addAttribute("appVersionList", appVersionList);
		return "developer/appinfoview";
	}

	/**
	 * 根据id修改界面
	 * 
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "appinfomodify")
	public String appinfomodify(@RequestParam Integer id, Model model) {
		// 查询所属平台
		List<DataDictionary> flatFormList = new ArrayList<DataDictionary>();
		flatFormList = dataDictionaryService.flatformList();
		model.addAttribute("flatFormList", flatFormList);

		AppInfo appInfo = new AppInfo();
		appInfo = appInfoService.getAppInfo(id, null);
		model.addAttribute("appInfo", appInfo);
		return "developer/appinfomodify";
	}

	/**
	 * 修改App基础信息
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "appinfomodifysave")
	public String appinfomodifySave(AppInfo appInfo, HttpSession session,
			@RequestParam(value = "attach", required = false) MultipartFile attach, Model model) {
		int result = 0;
		try {
			String idPicPath = null;
			String logoLocPath = null;
			// 判断文件是否为空
			if (!attach.isEmpty()) {
				String path = session.getServletContext().getRealPath("statics" + File.separator + "uploadfiles");
				String oldFileName = attach.getOriginalFilename();// 原文件
				String prefix = FilenameUtils.getExtension(oldFileName);// 原文件后缀名
				int filesize = 500000;
				if (attach.getSize() > filesize) {
					model.addAttribute("fileUploadError", "*上传大小不得超过500KB");
					return "developer/appinfomodify";
				} else if (prefix.equalsIgnoreCase("jpg") || prefix.equalsIgnoreCase("png")
						|| prefix.equalsIgnoreCase("jpeg") || prefix.equalsIgnoreCase("pneg")) {
					String fileName = appInfo.getAPKName() + ".jpg";
					File targetFile = new File(path, fileName);
					if (!targetFile.exists()) {
						targetFile.mkdirs();
					}
					try {
						attach.transferTo(targetFile);
					} catch (Exception e) {
						e.printStackTrace();
						model.addAttribute("fileUploadError", "上传失败！");
						return "developer/appinfomodify";
					}
					idPicPath = "/AppInfoSystem/statics/uploadfiles/" + fileName;
					logoLocPath = path + File.separator + fileName;
				} else {
					model.addAttribute("fileUploadError", "* 上传图片格式不正确！");
					return "developer/appinfomodify";
				}
			}
			appInfo.setLogoLocPath(logoLocPath);
			appInfo.setLogoPicPath(idPicPath);
			appInfo.setModifyDate(new Date());
			appInfo.setModifyBy(((DevUser) session.getAttribute(Constants.USER_SESSION)).getId());
			result = appInfoService.modify(appInfo);
		} catch (Exception e) {
			e.printStackTrace();
			return "403";
		}
		if (result > 0) {
			return "redirect:list";
		} else {
			return "redirect:appinfomodify";
		}
	}

	/**
	 * 删除App基础信息
	 * 
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "delapp.json")
	@ResponseBody
	public Object delapp(@RequestParam Integer id, Model model) {
		HashMap<String, String> resultMap = new HashMap<String, String>();
		if (id == 0) {
			resultMap.put("delResult", "notexist");
		} else {
			int result = appInfoService.deleteById(id);
			if (result > 0)
				resultMap.put("delResult", "true");
			else
				resultMap.put("delResult", "false");
		}
		return JSONArray.toJSONString(resultMap);
	}

	/**
	 * 显示修改版本信息
	 * 
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "appversionmodify")
	public String appversionModify(Integer aid, Integer vid, Model model) {
		// 根据id查看App历史版本
		List<AppVersion> appVersionList = new ArrayList<AppVersion>();
		appVersionList = appVersionService.getIdVersions(aid);

		AppVersion appVersion = appVersionService.findIdvVersion(vid);
		model.addAttribute("appVersionList", appVersionList);
		model.addAttribute("appVersion", appVersion);
		return "developer/appversionmodify";
	}

	/**
	 * 显示新增版本信息
	 * 
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "appversionadd")
	public String appversionAdd(Integer id, Model model) {
		// 根据id查看App历史版本
		List<AppVersion> appVersionList = new ArrayList<AppVersion>();
		appVersionList = appVersionService.getIdVersions(id);

		AppInfo appInfo = appInfoService.getAppInfo(id, null);
		model.addAttribute("appVersionList", appVersionList);
		model.addAttribute("appVersion", appInfo);
		return "developer/appversionadd";
	}

	/**
	 * 新增版本信息
	 * 
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "addversionsave")
	public String addversionSave(AppVersion appVersion, Integer appId, String appName, HttpSession session,
			@RequestParam(value = "a_downloadLink", required = false) MultipartFile attach, Model model) {
		String apkLocPath = null;
		String apkFileName = null;
		String downloadLink = null;
		// 判断文件是否为空
		if (!attach.isEmpty()) {
			String path = session.getServletContext().getRealPath("statics" + File.separator + "uploadfiles");
			String oldFileName = attach.getOriginalFilename();// 原文件
			String prefix = FilenameUtils.getExtension(oldFileName);// 原文件后缀名
			int filesize = 500000000;
			if (attach.getSize() > filesize) {
				model.addAttribute("fileUploadError", "*上传大小不得超过500MB");
				return "developer/appinfoadd";
			} else if (prefix.equalsIgnoreCase("apk")) {
				String fileName = attach.getOriginalFilename();
				File targetFile = new File(path, fileName);
				if (!targetFile.exists()) {
					targetFile.mkdirs();
				}
				try {
					attach.transferTo(targetFile);
				} catch (Exception e) {
					e.printStackTrace();
					model.addAttribute("fileUploadError", "上传失败！");
					return "developer/appinfoadd";
				}
				downloadLink = "/AppInfoSystem/statics/uploadfiles/" + fileName;
				apkLocPath = path + File.separator + fileName;
				apkFileName = fileName;
			} else {
				model.addAttribute("fileUploadError", "* 上传软件格式不正确！");
				return "developer/appinfoadd";
			}
		}
		try {
			appVersion.setDownloadLink(downloadLink);
			appVersion.setApkLocPath(apkLocPath);
			appVersion.setApkFileName(apkFileName);
			appVersion.setCreationDate(new Date());
			appVersion.setAppId(appId);
			appVersion.setCreatedBy(((DevUser) session.getAttribute(Constants.USER_SESSION)).getId());
		} catch (Exception e) {
			e.printStackTrace();
			return "403";
		}
			appVersionService.add(appVersion);
			AppVersion appVersionId = appVersionService.findAppId(appId);
		if (appInfoService.updateVersionId(appVersionId.getId(), appId)) {
			return "redirect:list";
		} else {
			return "redirect:appversionadd";
		}

	}

	/**
	 * 修改版本信息
	 * 
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "appversionmodifysave")
	public String appversionmodifysave(@RequestParam(value = "attach", required = false) MultipartFile attach,
			Model model, AppVersion appVersion, HttpSession session) {
		int result = 0;
		try {
			String apkLocPath = null;
			String apkFileName = null;
			String downloadLink = null;
			// 判断文件是否为空
			if (!attach.isEmpty()) {
				String path = session.getServletContext().getRealPath("statics" + File.separator + "uploadfiles");
				String oldFileName = attach.getOriginalFilename();// 原文件
				String prefix = FilenameUtils.getExtension(oldFileName);// 原文件后缀名
				int filesize = 500000000;
				if (attach.getSize() > filesize) {
					model.addAttribute("fileUploadError", "*上传大小不得超过500MB");
					return "developer/appversionmodify";
				} else if (prefix.equalsIgnoreCase("apk")) {
					String fileName = attach.getOriginalFilename();
					File targetFile = new File(path, fileName);
					if (!targetFile.exists()) {
						targetFile.mkdirs();
					}
					try {
						attach.transferTo(targetFile);
					} catch (Exception e) {
						e.printStackTrace();
						model.addAttribute("fileUploadError", "上传失败！");
						return "developer/appversionmodify";
					}
					downloadLink = "/AppInfoSystem/statics/uploadfiles/" + fileName;
					apkLocPath = path + File.separator + fileName;
					apkFileName = fileName;
				} else {
					model.addAttribute("fileUploadError", "* 上传软件格式不正确！");
					return "developer/appversionmodify";
				}
				appVersion.setDownloadLink(downloadLink);
				appVersion.setApkLocPath(apkLocPath);
				appVersion.setApkFileName(apkFileName);
				appVersion.setModifyDate(new Date());
				appVersion.setModifyBy(((DevUser) session.getAttribute(Constants.USER_SESSION)).getId());
			}
			result = appVersionService.modify(appVersion);
			if (result > 0) {
				return "redirect:list";
			} else {
				return "redirect:appversionmodify";
			}
		} catch (Exception e) {
			e.printStackTrace();
			return "403";
		}
	}

	/**
	 * App软件上下架
	 */
	@RequestMapping(value = "sale.json")
	@ResponseBody
	public Object sale(Integer id, String obj, Model model) {
		HashMap<String, String> resultMap = new HashMap<String, String>();
		resultMap.put("errorCode", "0");
		if (obj.equals("open")) {
			int result = appInfoService.sale(4, id);
			if (result > 0) {
				resultMap.put("resultMsg", "success");
			} else {
				resultMap.put("resultMsg", "failed");
			}
		} else {
			int result = appInfoService.sale(5, id);
			if (result > 0) {
				resultMap.put("resultMsg", "success");
			} else {
				resultMap.put("resultMsg", "failed");
			}
		}
		return JSONArray.toJSONString(resultMap);
	}

	/**
	 * 删除apk文件
	 */
	@RequestMapping(value = "delfile.json")
	@ResponseBody
	public Object delfile(Integer id, String flag, String path) {
		HashMap<String, String> resultMap = new HashMap<String, String>();
		int result = appInfoService.delfile(id, flag);
		if (result == 1) {
			File file = new File(path);
			if (file.delete()) {
				resultMap.put("result", "success");
			} else {
				resultMap.put("result", "failed");
			}
		}
		return JSONArray.toJSONString(resultMap);
	}
}
